/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socket.chat;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author atsi
 */
public class ChatClient implements Runnable {
    
    private Socket SOCKET;
    private Scanner INPUT;
    private Scanner SEND = new Scanner(System.in);
    private PrintWriter OUT;
    
    public ChatClient(Socket clientSocket) {
        this.SOCKET = clientSocket;
    }
    
    public void run() {
        try {
            try {
                INPUT = new Scanner(SOCKET.getInputStream());
                OUT = new PrintWriter(SOCKET.getOutputStream());
                OUT.flush();
                CheckStream();
            } finally {
                SOCKET.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void Disconnect() throws IOException {
        OUT.println(ChatClientGUI.userName + " has disconnected!");
        OUT.flush();
        SOCKET.close();
        JOptionPane.showMessageDialog(null, "You disconnected!");
        System.exit(0);
        
    }
    
    public void CheckStream() {
        
        while (true) {
            Receive();
        }
    }
    
    public void Receive() {
        if (INPUT.hasNext()) {
            String MESSAGE = INPUT.nextLine();
            if (MESSAGE.contains("#?!")) {
                String temp1 = MESSAGE.substring(3);
                temp1 = temp1.replace("[", "");
                temp1 = temp1.replace("]", "");
                
                String[] CurrentUsers = temp1.split(", ");
                ChatClientGUI.JL_ONLINE.setListData(CurrentUsers);
            } else {
                ChatClientGUI.TA_CONVERSATION.append(MESSAGE + "\n");
            }
            
        }
    }

    public void Send(String x) {
        
        OUT.println(ChatClientGUI.userName + ": " + x);
        OUT.flush();
        ChatClientGUI.TF_Message.setText("");
        
    }
}
